// 获取canvas和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 定义格子大小
const box = 20;
// 定义画布宽高的格子数
const widthCount = canvas.width / box;
const heightCount = canvas.height / box;

// 初始化蛇
let snake = [
    { x: 7 * box, y: 10 * box },
    { x: 6 * box, y: 10 * box },
    { x: 5 * box, y: 10 * box }
];

// 初始化方向
let direction = 'RIGHT';
// 新增：加速状态
let isSpeedUp = false;
// 新增：加速定时器
let speedUpTimer = null;
// 初始化食物
let food = {};
// 初始化分数
let score = 0;
// 游戏是否结束
let gameOver = false;

// 获取当前模式
let mode = 'classic';
const modeSelect = document.getElementById('mode');
if (modeSelect) {
    mode = modeSelect.value;
    modeSelect.addEventListener('change', function() {
        mode = this.value;
    });
}

// 障碍物数组
let obstacles = [];
// 障碍物数量
const OBSTACLE_COUNT = 8;

// 创建游戏结束弹窗元素
const gameOverModal = document.createElement('div');
gameOverModal.id = 'gameOverModal';
gameOverModal.style.display = 'none';
gameOverModal.innerHTML = `
    <div class="modal-content">
        <h2>游戏结束！</h2>
        <p id="finalScore"></p>
        <button id="restartBtn">重新开始</button>
    </div>
`;
document.body.appendChild(gameOverModal);

// 监听重开按钮
function bindRestartBtn() {
    const restartBtn = document.getElementById('restartBtn');
    if (restartBtn) {
        restartBtn.onclick = function() {
            window.location.reload();
        };
    }
}

// 生成障碍物
function createObstacles() {
    obstacles = [];
    for (let i = 0; i < OBSTACLE_COUNT; i++) {
        let obs;
        while (true) {
            obs = {
                x: Math.floor(Math.random() * widthCount) * box,
                y: Math.floor(Math.random() * heightCount) * box
            };
            // 不与蛇身、食物、已有障碍重叠
            let onSnake = snake.some(segment => segment.x === obs.x && segment.y === obs.y);
            let onFood = food.x === obs.x && food.y === obs.y;
            let onObstacle = obstacles.some(o => o.x === obs.x && o.y === obs.y);
            if (!onSnake && !onFood && !onObstacle) break;
        }
        obstacles.push(obs);
    }
}

// 生成食物位置
function createFood() {
    let newFood;
    while (true) {
        newFood = {
            x: Math.floor(Math.random() * widthCount) * box,
            y: Math.floor(Math.random() * heightCount) * box
        };
        // 确保食物不生成在蛇身和障碍物上
        let onSnake = snake.some(segment => segment.x === newFood.x && segment.y === newFood.y);
        let onObstacle = obstacles.some(o => o.x === newFood.x && o.y === newFood.y);
        if (!onSnake && !onObstacle) break;
    }
    food = newFood;
}

// 监听键盘事件，控制方向和加速
window.addEventListener('keydown', function(e) {
    switch (e.key) {
        case 'ArrowLeft':
            if (direction !== 'RIGHT') direction = 'LEFT';
            break;
        case 'ArrowUp':
            if (direction !== 'DOWN') direction = 'UP';
            break;
        case 'ArrowRight':
            if (direction !== 'LEFT') direction = 'RIGHT';
            break;
        case 'ArrowDown':
            if (direction !== 'UP') direction = 'DOWN';
            break;
    }
    // 新增：长按1秒后加速
    if (["ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown"].includes(e.key)) {
        if (!speedUpTimer && !isSpeedUp) {
            speedUpTimer = setTimeout(function() {
                isSpeedUp = true;
                speedUpTimer = null;
            }, 400);
        }
    }
});
// 新增：松开方向键时取消加速和定时器
window.addEventListener('keyup', function(e) {
    if (["ArrowLeft", "ArrowUp", "ArrowRight", "ArrowDown"].includes(e.key)) {
        isSpeedUp = false;
        if (speedUpTimer) {
            clearTimeout(speedUpTimer);
            speedUpTimer = null;
        }
    }
});

// 绘制游戏
function draw() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // 绘制障碍物（仅障碍模式）
    if (mode === 'obstacle') {
        ctx.fillStyle = '#795548';
        for (let i = 0; i < obstacles.length; i++) {
            ctx.fillRect(obstacles[i].x, obstacles[i].y, box, box);
            ctx.strokeStyle = '#fff';
            ctx.strokeRect(obstacles[i].x, obstacles[i].y, box, box);
        }
    }
    // 绘制蛇
    for (let i = 0; i < snake.length; i++) {
        ctx.fillStyle = i === 0 ? '#388e3c' : '#4caf50';
        ctx.fillRect(snake[i].x, snake[i].y, box, box);
        ctx.strokeStyle = '#fff';
        ctx.strokeRect(snake[i].x, snake[i].y, box, box);
    }
    // 绘制食物
    ctx.fillStyle = '#e53935';
    ctx.fillRect(food.x, food.y, box, box);
}

// 更新游戏状态
function update() {
    if (gameOver) return;
    // 获取蛇头
    const head = { x: snake[0].x, y: snake[0].y };
    // 根据方向移动
    switch (direction) {
        case 'LEFT':
            head.x -= box;
            break;
        case 'UP':
            head.y -= box;
            break;
        case 'RIGHT':
            head.x += box;
            break;
        case 'DOWN':
            head.y += box;
            break;
    }
    // 判断是否撞墙或撞到自己
    if (
        head.x < 0 || head.x >= canvas.width ||
        head.y < 0 || head.y >= canvas.height ||
        snake.some(segment => segment.x === head.x && segment.y === head.y)
    ) {
        gameOver = true;
        // 显示自定义弹窗
        document.getElementById('finalScore').textContent = '您的得分：' + score;
        gameOverModal.style.display = 'flex';
        bindRestartBtn();
        return;
    }
    // 判断是否撞到障碍物（仅障碍模式）
    if (mode === 'obstacle' && obstacles.some(o => o.x === head.x && o.y === head.y)) {
        gameOver = true;
        document.getElementById('finalScore').textContent = '您的得分：' + score;
        gameOverModal.style.display = 'flex';
        bindRestartBtn();
        return;
    }
    // 判断是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        snake.unshift(head); // 增加蛇身
        score++;
        document.getElementById('score').textContent = score;
        createFood();
        // 障碍模式下，吃到食物后可增加障碍
        if (mode === 'obstacle') {
            createObstacles();
        }
    } else {
        snake.unshift(head);
        snake.pop();
    }
}

// 游戏主循环
function gameLoop() {
    update();
    draw();
    if (!gameOver) {
        // 新增：根据加速状态调整速度
        setTimeout(gameLoop, isSpeedUp ? 60 : 120);
    }
}

// 背景切换功能
const backgrounds = ['bg1', 'bg2', 'bg3', 'bg4', 'bg5'];
let bgIndex = 0;
const body = document.body;
const bgSwitchBtn = document.getElementById('bg-switch');

function switchBackground() {
    // 移除所有背景类
    backgrounds.forEach(bg => body.classList.remove(bg));
    // 添加当前背景类
    body.classList.add(backgrounds[bgIndex]);
    // 下次切换到下一个
    bgIndex = (bgIndex + 1) % backgrounds.length;
}

bgSwitchBtn.addEventListener('click', switchBackground);

// 初始化
function init() {
    // 障碍模式下先生成障碍
    if (mode === 'obstacle') {
        createObstacles();
    }
    createFood();
    document.getElementById('score').textContent = score;
    switchBackground();
    // 不直接启动游戏循环，等待点击开始按钮
}

// 处理开始游戏按钮逻辑
const startBtn = document.getElementById('startBtn');
if (startBtn) {
    startBtn.style.display = 'block'; // 初始显示
    startBtn.onclick = function() {
        startBtn.style.display = 'none'; // 隐藏按钮
        gameLoop(); // 启动游戏主循环
    };
}

init(); 